// 单词验证和建议工具

import { WordSuggestion } from '../types';

// 常用英语单词库（按难度分类）
const WORD_CATEGORIES = {
  beginner: [
    'cat', 'dog', 'house', 'car', 'book', 'water', 'food', 'happy', 'run', 'big',
    'small', 'red', 'blue', 'green', 'sun', 'moon', 'tree', 'flower', 'bird', 'fish'
  ],
  intermediate: [
    'beautiful', 'important', 'interesting', 'different', 'necessary', 'possible',
    'understand', 'remember', 'decide', 'explain', 'create', 'develop', 'improve',
    'experience', 'knowledge', 'education', 'communication', 'relationship', 'opportunity'
  ],
  advanced: [
    'sophisticated', 'inevitable', 'comprehensive', 'fundamental', 'revolutionary',
    'unprecedented', 'extraordinary', 'philosophical', 'psychological', 'technological',
    'manifestation', 'implementation', 'transformation', 'consciousness', 'responsibility'
  ]
};

// 单词验证规则
const WORD_PATTERN = /^[a-zA-Z]+$/;
const MIN_WORD_LENGTH = 2;
const MAX_WORD_LENGTH = 20;

class WordValidator {
  // 验证单词是否有效
  isValidWord(word: string): boolean {
    if (!word || typeof word !== 'string') return false;
    
    const trimmed = word.trim().toLowerCase();
    
    // 检查长度
    if (trimmed.length < MIN_WORD_LENGTH || trimmed.length > MAX_WORD_LENGTH) {
      return false;
    }
    
    // 检查格式（只允许字母）
    if (!WORD_PATTERN.test(trimmed)) {
      return false;
    }
    
    return true;
  }

  // 验证单词列表
  validateWordList(words: string[]): { valid: string[], invalid: string[], errors: string[] } {
    const valid: string[] = [];
    const invalid: string[] = [];
    const errors: string[] = [];
    
    words.forEach(word => {
      if (this.isValidWord(word)) {
        const cleanWord = word.trim().toLowerCase();
        if (!valid.includes(cleanWord)) {
          valid.push(cleanWord);
        }
      } else {
        invalid.push(word);
        if (!word || word.trim() === '') {
          errors.push('空单词不允许');
        } else if (word.length < MIN_WORD_LENGTH) {
          errors.push(`单词 "${word}" 太短（最少${MIN_WORD_LENGTH}个字母）`);
        } else if (word.length > MAX_WORD_LENGTH) {
          errors.push(`单词 "${word}" 太长（最多${MAX_WORD_LENGTH}个字母）`);
        } else if (!WORD_PATTERN.test(word)) {
          errors.push(`单词 "${word}" 包含非法字符`);
        }
      }
    });
    
    return { valid, invalid, errors };
  }

  // 获取单词建议
  getWordSuggestions(input: string = '', difficulty: string = 'intermediate'): WordSuggestion[] {
    const allWords = [
      ...WORD_CATEGORIES.beginner.map(word => ({ word, frequency: 100, category: 'beginner' })),
      ...WORD_CATEGORIES.intermediate.map(word => ({ word, frequency: 80, category: 'intermediate' })),
      ...WORD_CATEGORIES.advanced.map(word => ({ word, frequency: 60, category: 'advanced' }))
    ];
    
    if (!input) {
      // 返回指定难度的随机单词
      return allWords
        .filter(item => item.category === difficulty)
        .sort(() => Math.random() - 0.5)
        .slice(0, 10);
    }
    
    // 根据输入过滤匹配的单词
    const filtered = allWords.filter(item => 
      item.word.toLowerCase().includes(input.toLowerCase())
    );
    
    return filtered
      .sort((a, b) => b.frequency - a.frequency)
      .slice(0, 10);
  }

  // 检查单词难度
  getWordDifficulty(word: string): 'beginner' | 'intermediate' | 'advanced' {
    const lowerWord = word.toLowerCase();
    
    if (WORD_CATEGORIES.beginner.includes(lowerWord)) {
      return 'beginner';
    } else if (WORD_CATEGORIES.intermediate.includes(lowerWord)) {
      return 'intermediate';
    } else if (WORD_CATEGORIES.advanced.includes(lowerWord)) {
      return 'advanced';
    }
    
    // 默认根据长度判断
    if (lowerWord.length <= 4) return 'beginner';
    if (lowerWord.length <= 8) return 'intermediate';
    return 'advanced';
  }

  // 获取随机单词组合
  getRandomWordSet(count: number = 5, difficulty: string = 'intermediate'): string[] {
    const words = WORD_CATEGORIES[difficulty as keyof typeof WORD_CATEGORIES] || WORD_CATEGORIES.intermediate;
    const shuffled = [...words].sort(() => Math.random() - 0.5);
    return shuffled.slice(0, Math.min(count, words.length));
  }
}

export const wordValidator = new WordValidator();